﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using Lumberjack.BusinessLogic;

namespace Lumberjack
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // do tworzenia logów
        IRepository<Contest> _contestService;
        public static LumberjackEntities1 context = new LumberjackEntities1();         //baza?

        public MainWindow()
        {
            InitializeComponent();
            _contestService = new RepositoryService<Contest>(MainWindow.context);

            tbName.Text = "Konkurs " + DateTime.Now;

            ReloadContestItems();
        }

        private void ReloadContestItems()
        {   
            cbLoad.Items.Clear();
            var contestService = _contestService.GetAll().ToList();
            foreach (var s in contestService)
            {
                cbLoad.Items.Add(s);
            }
            cbLoad.SelectedIndex = 0;
        }


        private void bNewCompetition_Click(object sender, RoutedEventArgs e)
        {
            List<string> str = new List<string>() { tbCompetitionI.Text, tbCompetitionII.Text, tbCompetitionIII.Text, tbCompetitionIV.Text, tbCompetitionV.Text };
            if(str.ExistsNullOrEmpty())
            {
                MessageBox.Show("Przynajmniej jedna z rund nie zawiera numeru, proszę uzupełnij wszystkie rundy.", "Brak numeru", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            Contest contest = new Contest()                
            {
                competition_1 = Convert.ToByte(tbCompetitionI.Text),
                competition_2 = Convert.ToByte(tbCompetitionII.Text),
                competition_3 = Convert.ToByte(tbCompetitionIII.Text),
                competition_4 = Convert.ToByte(tbCompetitionIV.Text),
                competition_5 = Convert.ToByte(tbCompetitionV.Text),
                C_date = DateTime.Now
            };
            
            if (!string.IsNullOrEmpty(tbName.Text))
            {
                contest.C_name = tbName.Text;
            }
            else
            {
               contest.C_name = "Konkurs " + contest.C_date;
            }

            _contestService.Insert(contest);

            CompetitionWindow cw = new CompetitionWindow(contest);
            cw.Show();
            this.Close();
        }

        private void tbCompetitionI_KeyDown(object sender, KeyEventArgs e)
        {
            Validation.OnlyNumbersAndCommas(e, tbCompetitionI);
        }

        private void tbCompetitionII_KeyDown(object sender, KeyEventArgs e)
        {
            Validation.OnlyNumbersAndCommas(e, tbCompetitionII);
        }

        private void tbCompetitionIII_KeyDown(object sender, KeyEventArgs e)
        {
            Validation.OnlyNumbersAndCommas(e, tbCompetitionIII);
        }

        private void tbCompetitionIV_KeyDown(object sender, KeyEventArgs e)
        {
            Validation.OnlyNumbersAndCommas(e, tbCompetitionIV);
        }

        private void tbCompetitionV_KeyDown(object sender, KeyEventArgs e)
        {
            Validation.OnlyNumbersAndCommas(e, tbCompetitionV);
        }

        private void bLoadCompetition_Click(object sender, RoutedEventArgs e)
        {
            string m = cbLoad.SelectedItem.ToString();
            var competition = _contestService.GetAll().Where(s => s.C_name == m).FirstOrDefault();
            CompetitionWindow cw = new CompetitionWindow(competition, true);
            cw.Show();
            this.Close();
        }

        private void bImport_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog fld = new Microsoft.Win32.OpenFileDialog();
            fld.DefaultExt = ".xml";
            fld.Filter = "XML files (*.xml)|*.xml";
            fld.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            bool? result = fld.ShowDialog();
            if (result == true)
            {

                XMLExportContest hxand = new XMLExportContest(fld.FileName);
                hxand.newTable("Competitor");
                int res = -3;
                try
                {
                    res = hxand.importTables();
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message, ex);
                    MessageBox.Show("Import konkursu zakończony niepowodzeniem, plik jest uszkodzony", "Import nieudany", MessageBoxButton.OK, MessageBoxImage.Error);                  
                }

                if (res == 0)
                {
                    MessageBox.Show("Import konkursu zakończony powodzeniem", "Import udany", MessageBoxButton.OK, MessageBoxImage.Information);
                    ReloadContestItems();
                }
                else if(res == -1)
                {
                    MessageBox.Show("Import konkursu zakończony niepowodzeniem, podany konkurs już istnieje w bazie", "Import nieudany", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else if (res == -2)
                {
                    MessageBox.Show("Import konkursu zakończony niepowodzeniem, podany plik nie jest plikiem konkursu lub jest uszkodzony i nie nadaje się do importu", "Import nieudany", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            
        }

        private void bExport_Click(object sender, RoutedEventArgs e)
        {
            if (cbLoad.SelectedItem != null)
            {
                Contest c = cbLoad.SelectedItem as Contest;
 

                Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
                sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                sfd.Filter = "XML files (*.xml)|*.xml";
                sfd.FileName = c.C_name.Replace(":", "_") + ".xml";

                if (sfd.ShowDialog() == true)
                {
                    try
                    {
                        XMLExportContest xm = new XMLExportContest(sfd.FileName);
                        xm.exportTable(c);
                        MessageBox.Show("Eksport udany", "Eksport udany", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    catch(Exception ex)
                    {
                        log.Error(ex.Message, ex);
                        MessageBox.Show("Eksport nieudany, wystąpił błąd podczas próby zapisu pliku, spróbuj zapisać plik w innym miejscu", "Eksport nieudany", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }


            }
        }

        private void bDelete_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult mr = MessageBox.Show("Czy na pewno chcesz usunąć ten konkurs?", "Czy usunąć?", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (mr == MessageBoxResult.Yes && cbLoad.SelectedIndex != -1)
            {
                string item = cbLoad.SelectedItem.ToString();
                var cnt = _contestService.GetAll().Where(d => d.C_name == item).FirstOrDefault();
                _contestService.Delete(cnt);

                ReloadContestItems();
                MessageBox.Show("Konkurs usunięty!", "Usuń", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

    }
}
